import Taro, { useDidShow, getCurrentInstance } from '@tarojs/taro';
import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'react-redux';
import { View, Button, Text, Input, Image, Picker } from '@tarojs/components';
import right from '@/images/common/rightGray.png';
import { debounce } from '@/utils/helper';
import Icon from '@/components/Icon';
import { customeColor } from '@/src/config';
import { regeo } from '@/dataTransfer/address';
import classNames from 'classnames';

import './index.scss';

let chooseLocation;

if (process.env.TARO_ENV === 'h5') {
  chooseLocation = {
    setLocation: () => {},
    getLocation: () => {
      const params = new URLSearchParams(window.location.href.replace(/.*?\?/, ''));

      const name = params.get('name');
      const [latitude, longitude] = (params.get('latng') || '').split(',');
      const address = params.get('addr');
      const city = params.get('city');

      if (!address || !city || !longitude || !latitude) {
        return null;
      }

      return {
        name,
        longitude,
        latitude,
        address,
        city,
      };
    },
  };
}

const AddAddress = ({ dispatch, loading }) => {
  const isLoading = [
    loading.effects['giftCard/adressNewAddModel'],
    loading.effects['giftCard/allAddressesModel'],
    loading.effects['giftCard/adressNewEditModel'],
  ].some((v) => v === true);
  isLoading ? Taro.showLoading({ title: '' }) : null;
  const { router } = getCurrentInstance();
  const { params = {} } = router;

  const isUseLocationPicker = useRef(false);

  const addressId = params.id;
  const [atSwitch, setAtSwitch] = useState(false);
  const [address, setAddress] = useState();
  const [districtRegionCode, setDistrictRegionCode] = useState();
  const [houseNumber, setHouseNumber] = useState();
  const [contactName, setContactName] = useState();
  const [mobile, setMobile] = useState();
  const [editFlag, setEditFlag] = useState('add');
  const [curTag,setCurTag] = useState('家')

  const [coordinate, setCoordinate] = useState({ latitude: 0, longitude: 0 });

  const inputHandler = (key, e) => {
    switch (key) {
      case 'address':
        setAddress(e.detail.value);
        break;
      case 'houseNumber':
        setHouseNumber(e.detail.value);
        break;
      case 'contactName':
        setContactName(e.detail.value);
        break;
      case 'mobile':
        setMobile(e.detail.value);
        break;
    }
  };

  useEffect(() => {
    if (addressId) {
      Taro.setNavigationBarTitle({
        title:'修改地址'
      })
      dispatch({ type: 'giftCard/adressDetailModel', payload: { id: addressId } }).then((res) => {
        setAtSwitch(res.isDefault === '1');

        // 从 地址选择器返回的不设置
        if (!isUseLocationPicker.current) {
          setAddress(res.address);
          setHouseNumber(res.houseNumber);

          setCoordinate({
            latitude: res.latitude,
            longitude: res.longitude,
          });

          isUseLocationPicker.current = false;
        }
        setCurTag(res.tag)
        setContactName(res.contactName);
        setMobile(parseInt(res.mobile));
      });
      setEditFlag('edit');
    } else {
      setEditFlag('add');
    }
  }, [addressId]);

  const handleChangeAtSwitch = () => {
    setAtSwitch(!atSwitch);
  };

  const deleteAddress = debounce(() => {
    dispatch({
      type: 'giftCard/adressDeleteModel',
      payload: {
        addressId,
      },
    }).then(() => {
      return dispatch({
        type: 'giftCard/allAddressesModel',
        payload: { setDefaultAddress: false },
      });
    });
  }, 1000);

  const add = debounce(async () => {
    let isDefault = null;
    if (atSwitch) {
      isDefault = 1;
    } else {
      isDefault = 0;
    }

    const addressPayload = {
      address: (address ?? '').trim(),
      houseNumber: (houseNumber ?? '').trim(),
      contactName: (contactName ?? '').trim(),
      mobile,
      districtRegionCode,
      isDefault,
      tag:curTag,
      ...coordinate,
    };

    if (!addressPayload.address) {
      Taro.showToast({
        title: '所在地区不能为空',
        icon: 'none',
      });
      return false;
    } else if (!addressPayload.houseNumber) {
      Taro.showToast({
        title: '详细地址不能为空',
        icon: 'none',
      });
      return false;
    } else if (!addressPayload.contactName) {
      Taro.showToast({
        title: '收货人不能为空',
        icon: 'none',
      });
      return false;
    }

    if (houseNumber.length > 60) {
      Taro.showToast({
        title: '详细地址最多60个字符',
        icon: 'none',
      });
      return false;
    }

    if (!/^1[3456789]\d{9}$/.test(addressPayload.mobile)) {
      Taro.showToast({
        title: '请填写正确的手机号',
        icon: 'none',
      });
      return false;
    }
    if (editFlag === 'add') {
      dispatch({
        type: 'giftCard/adressNewAddModel',
        payload: {
          ...addressPayload,
        },
      })
        .then(() => {
          return dispatch({
            type: 'giftCard/allAddressesModel',
            payload: { setDefaultAddress: false },
          });
        })
        .then(() => {
          return Taro.navigateBack();
        });
    } else {
      dispatch({
        type: 'giftCard/adressNewEditModel',
        payload: {
          parmas: {
            ...addressPayload,
          },
          id: addressId,
        },
      })
        .then(() => {
          return dispatch({
            type: 'giftCard/allAddressesModel',
            payload: { setDefaultAddress: false },
          });
        })
        .then(() => {
          return Taro.navigateBack();
        });
    }
  }, 2000);

  // 地图选择地址完成之后, 获取选择的地址
  useDidShow(() => {
    // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    const location = chooseLocation?.getLocation();
    if (!location) {
      return;
    }

    const { latitude, longitude } = location;
    regeo({ latitude, longitude })
      .then((data) => {
        isUseLocationPicker.current = true;

        setAddress(location.address);
        setHouseNumber('');

        setCoordinate({ latitude, longitude });
        setDistrictRegionCode(data.adcode);
      })
      .catch((e) => {
        console.warn(e);

        Taro.showToast({
          title: '获取行政编码失败',
          icon: 'none',
        });
      });
  });

  useEffect(() => {
    return () => {
      chooseLocation?.setLocation(null);
    };
  }, []);
  const tagsArr = ['家','公司','学校']
  return (
    <View className="addAddress">
      <View className="addrForm">
        <View className="listWrap">
          <Text className="text">收货人</Text>
          <input
            className="code-input"
            type="text"
            placeholder="请填写收货人姓名"
            placeholderClass="inputPlaceholder"
            value={contactName}
            onInput={(e) => {
              inputHandler('contactName', e);
            }}
          />
        </View>
        <View className="listWrap">
          <Text className="text">手机号码</Text>
          <input
            className="code-input"
            type="number"
            placeholder="请填写收货人手机号码"
            placeholderClass="inputPlaceholder"
            maxlength={11}
            value={mobile}
            onInput={(e) => {
              inputHandler('mobile', e);
            }}
          />
        </View>
        <View className="listWrap">
          <View className="text">所在地区</View>
          <Picker mode='region' onChange={e=>{
            setAddress(e.detail?.value?.join(''))
            setDistrictRegionCode(e.detail?.code[e.detail?.code?.length-1])
          }}>
            <Text style={{color:address?'#26282A':'#96989A',fontSize:'14px'}}>{address || '请选择'}</Text>
          </Picker>
          <Image className='list-icon' src={require('@/orderSubPack/images/confirmOrder/right-icon.png')} />
        </View>
        <View className="listWrap">
          <Text className="text">详细地址</Text>
          <input
            className="code-input"
            type="text"
            placeholder="详细地址，例1幢201室"
            placeholderClass="inputPlaceholder"
            value={houseNumber}
            onInput={(e) => {
              inputHandler('houseNumber', e);
            }}
          />
        </View>
      </View>

      <View className="addrForm">
        <View className="listWrap">
          <Text className="text">地址标签</Text>
          <View className="list-tags">
            {tagsArr.map((res)=>(
              <View className={classNames('tags-item',{'customePageStyle customePageStyleBg20':curTag==res})} onClick={()=>{setCurTag(res)}}>{res}</View>
            ))}
          </View>
        </View>
        <View className="listWrap">
          <Text className="text">设置默认地址</Text>
          <Image className='switch-img' src={require(`@/images/${atSwitch?'toggle-on':'toggle'}.svg`)} onClick={handleChangeAtSwitch}></Image>
        </View>
      </View>
      <View className="addAddress-button">
        {editFlag === 'edit' && (
          <Button className="btn-red del" onClick={deleteAddress}>
            删除地址
          </Button>
        )}
        <Button className="btn-red customePageBackgroundStyle" onClick={add}>保存并使用</Button>
      </View>
    </View>
  );
};
export default connect(({ giftCard, loading }) => ({
  loading,
  adressDetail: giftCard.adressDetail
}))(AddAddress);
